package index

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"gluenet/pkg/apis"
)

func IndexPut(ctx *apis.GlueContext) {
	var (
		err error
		req struct {
			List []interface{} `json:"list" yaml:"list" xorm:"list"`
		}
	)

	ctx.Logger.Debugf("recv index put")

	if err = ctx.WebContext.ReadJSON(&req); err != nil {
		ctx.WebContext.JSON(apis.ResponseReqErr(err, nil))
		return
	}

	var page = PageIndex{
		IdMap: make(map[string]interface{}),
		List:  []interface{}{},
	}

	for _, v := range req.List {
		bts, _ := json.Marshal(v)
		d := md5.Sum(bts)
		id := hex.EncodeToString(d[:])
		page.IdMap[id] = v
		page.List = append(page.List, v)
	}

	bts, _ := json.Marshal(page)

	if err = ctx.DataBase.PutIndex(string(bts)); err != nil {
		ctx.WebContext.JSON(apis.ResponseReqErr(err, nil))
		return
	}
	ctx.WebContext.JSON(apis.ResponseOK(nil))
}
